package org.example.dynamic.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.dynamic.enetity.FileInfo;
import org.example.dynamic.mapper.FileInfoMapper;
import org.example.dynamic.service.impl.IFileService;
import org.example.dynamic.util.BaseException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.Date;

/**
 * 文件处理service
 * 
 * @author Admin
 *
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileInfoMapper, FileInfo> implements IFileService {

    @Override
    public void upload(MultipartFile file) throws IOException {
        String base64 = convertToBase64(file);
        FileInfo info = new FileInfo();
        info.setName(file.getName());
        info.setBaseCode("baseCode");
        info.setState(1);
        info.setId(123L);
        info.setNumber(0);
        info.setCreateTime(new Date());
        baseMapper.insert(info);
    }

    /**
     * 文件转Base64
     */


    public String convertToBase64(MultipartFile file) throws IOException {
        byte[] bytes = file.getBytes();  // 直接获取字节数组
        return Base64.getEncoder().encodeToString(bytes);  // 编码为Base64字符串
    }

    @Override
    public FileInfo getById(Long id) {
        FileInfo fileInfo = baseMapper.selectById(id);
        if (fileInfo == null) {
            throw new BaseException("未查询到对应信息");
        }
        return fileInfo;
    }

    @Override
    public Object queryImage(Long id) {
        FileInfo fileInfo = baseMapper.selectById(id);
        if (fileInfo == null) {
            throw new BaseException("未查询到对应信息");
        }
        return fileInfo.getBaseCode();
    }

}
